# import tkinter as tk
# import tkinter.filedialog
# from PIL import ImageGrab
# import os
# # from PIL import ImageGrab
# from time import sleep
# class CaptureScreen(tk.Frame):
#     def __init__(self, master=None):
#         super().__init__(master)
#         self.master=master
#         self.pack()
#         self.initfield()
#         self.buttonCaptureClick()
#         self.create_widgets()
#     def initfield(self):
#         self.pngname="CaptureScreen.png"
#         self.pngpath=os.path.join(os.environ['temp'],self.pngname)

#     def create_widgets(self):
#         #变量X和Y用来记录鼠标左键按下的位置
#         self.X = tk.IntVar(value=0)
#         self.Y = tk.IntVar(value=0)
#         #屏幕尺寸
#         screenWidth = self.winfo_screenwidth()
#         screenHeight = self.winfo_screenheight()
#         #创建顶级组件容器
#         self.top = tk.Toplevel(self, width=screenWidth, height=screenHeight)
#         #不显示最大化、最小化按钮
#         self.top.overrideredirect(True)
#         self.canvas = tk.Canvas(self.top,bg='white', width=screenWidth, height=screenHeight)
#         #显示全屏截图，在全屏截图上进行区域截图
        
#         self.image = tk.PhotoImage(file=self.pngpath)
#         self.canvas.create_image(screenWidth//2, screenHeight//2, image=self.image)
#         self.canvas.pack()
#     def buttonCaptureClick(self):
#         #最小化主窗口
#         # self.master.state('icon')
#         im = ImageGrab.grab(bbox=None, include_layered_windows=False, all_screens=True)
#         im.save(self.pngpath)
#         im.close()
# app=CaptureScreen(tk.Tk())
# app.mainloop()







from time import sleep
from PIL import Image, ImageGrab
import tkinter,ctypes,os

class CTkPrScrn:
    def __init__(self,save=False):
        self.__start_x, self.__start_y = 0, 0
        self.__scale = 1

        self.initfield(save=save)

        #创建缓存
        self.__screen=ImageGrab.grab()

        self.__win = tkinter.Tk()
        self.__win.attributes("-alpha", 0.5)  # 设置窗口半透明
        self.__win.attributes("-fullscreen", True)  # 设置全屏
        self.__win.attributes("-topmost", True)  # 设置窗口在最上层

        self.__width, self.__height = self.__win.winfo_screenwidth(), self.__win.winfo_screenheight()

        # 创建画布
        self.__canvas = tkinter.Canvas(self.__win, width=self.__width, height=self.__height, bg="gray")

        self.__win.bind('<Button-1>', self.xFunc1)  # 绑定鼠标左键点击事件
        self.__win.bind('<ButtonRelease-1>', self.xFunc1)  # 绑定鼠标左键点击释放事件
        self.__win.bind('<B1-Motion>', self.xFunc2)  # 绑定鼠标左键点击移动事件
        self.__win.bind('<Escape>', lambda e: self.__win.destroy())  # 绑定Esc按键退出事件

        user32 = ctypes.windll.user32
        gdi32 = ctypes.windll.gdi32
        dc = user32.GetDC(None)
        widthScale = gdi32.GetDeviceCaps(dc, 8)  # 分辨率缩放后的宽度
        heightScale = gdi32.GetDeviceCaps(dc, 10)  # 分辨率缩放后的高度
        width = gdi32.GetDeviceCaps(dc, 118)  # 原始分辨率的宽度
        height = gdi32.GetDeviceCaps(dc, 117)  # 原始分辨率的高度
        self.__scale = width / widthScale
        # print(self.__width, self.__height, widthScale, heightScale, width, height, self.__scale)

        self.__win.mainloop()  # 窗口持久化

    def initfield(self,**kwargs):
        self.save=kwargs['save']
        self.pngname="CaptureScreen.png"
        self.pngpath=os.path.join(os.environ['temp'],self.pngname)

    def xFunc1(self, event):
        # print(f"鼠标左键点击了一次坐标是:x={g_scale * event.x}, y={g_scale * event.y}")
        if event.state == 8:  # 鼠标左键按下
            self.__start_x, self.__start_y = event.x, event.y
        elif event.state == 264:  # 鼠标左键释放
            if event.x == self.__start_x or event.y == self.__start_y:
                return
            x1,x2=sorted([self.__start_x,event.x])
            y1,y2=sorted([self.__start_y,event.y])
            
            self.im = self.__screen.crop((self.__scale * x1 + 1, self.__scale * y1 + 1,
                                 self.__scale * x2, self.__scale * y2))

            if self.save:
                self.save()
            self.__win.update()
            sleep(0.5)
            self.__win.destroy()

    def save(self):
        self.im.save(self.pngpath)
        print('保存成功')
    
    def getScreen(self):
        return self.im

    def xFunc2(self, event):
        # print(f"鼠标左键点击了一次坐标是:x={self.__scale * event.x}, y={self.__scale * event.y}")
        if event.x == self.__start_x or event.y == self.__start_y:
            return
        self.__canvas.delete("prscrn")
        self.__canvas.create_rectangle(self.__start_x, self.__start_y, event.x, event.y,
                                       fill='white', outline='red', tag="prscrn")
        # 包装画布
        self.__canvas.pack()

if __name__ == '__main__':
    prScrn = CTkPrScrn(save=True)